<template>
  <div class="page-container">
    <DynamicForm class="mt-4" :config="dyConfig" :questions="dyQuestions" />
    <DynamicTable :tables="dyTable" :config="dyTableConfig" :icons="dyIcons" ref="directoryRef" />
  </div>

  <HistoryDetail v-model:visible="state.showDetail" />
  <LogDetail v-if="state.showLogDetail && state.rowId !== ''" v-model:visible="state.showLogDetail" :rowId="state.rowId" />
</template>

<script lang="ts" setup>
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { HOST } from '@/config';
import { Api, advancedQueryPreview, advancedQueryArchivesTypeTree, advancedQueryBatchDownload, advancedQueryUpdateStatus } from '@/config/api/searchManage';
import { useUserStoreWithOut } from '@/store/modules/user';
import { filter } from 'rxjs/operators';
import { createVNode, getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import HistoryDetail from './components/historyDetail.vue';
import LogDetail from '@/views/logManage/archivesLog/components/logDetail.vue';
import indexService from './index.service';
import { Modal, message } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

const { proxy }: any = getCurrentInstance();

const directoryRef = ref(null);
const accessToken = useUserStoreWithOut().getToken;

const dyQuestions = reactive(indexService.getQuestions());
const dyConfig: any = {
  labelCol: 6,
  wrapperCol: 18,
  grid: 8,
  style: 'table-form',
  cancelSave: true,
  combinationMethod(msg) {
    dyTableConfig.queryUrl = Api.advancedQueryPage;
    dyTableConfig.params = { ...msg };
    directoryRef.value.getData();
  }
};

const dyTable = reactive(indexService.getTables());
const dyIcons = reactive(indexService.getIcons());
const dyTableConfig: any = {
  queryUrl: Api.advancedQueryPage,
  protType: 'post',
  scroll: { x: 2400, y: 540 },
  isScreen: true,
  isPagingLocalData: true,
  rowSelection: {
    type: 'checkbox',
    // 下载为false-禁用
    getCheckboxProps: (record) => ({
      disabled: !record.couldDownload
    })
  }
};

const state = reactive({
  searchName: '',
  showDetail: false,
  selectedKeys: [],
  treeData: [],
  showTree: true,
  rowId: '',
  showLogDetail: false
});

const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    // if (item.key === DYNAMICLOCALTABLE) {
    // state.showDetail = true;
    // }
    if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '预览') {
      advancedQueryPreview({ id: item.value.data.id, needRecord: true }).then((res) => {
        if (res && res.success) {
          window.open(res.data);
        }
      });
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '下载') {
      const url = `${Api.advancedQueryDownload}/${item.value.data.id}`;
      downloadFile(url);
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '日志') {
      state.rowId = item.value.data.id;
      state.showLogDetail = true;
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '下载') {
      // 所有分页选中数据全部下载
      // 第二页数据初始不选的情况
      if (!directoryRef.value.pagingLocalData[directoryRef.value.pagination.pageNumber]) {
        return message.warning('请先选中一个选项');
      }
      // 所有分页选中数据当中都没有当前分页的选中数据
      const result = directoryRef.value.dataList.value.some((obj) => {
        for (let item of directoryRef.value.pagingLocalData[directoryRef.value.pagination.pageNumber]) {
          return item.id !== obj.id;
        }
      });
      if (!result && directoryRef.value.pagingLocalData.length !== 0) {
        message.warning('请先选中一个选项');
        return;
      }
      // 所有分页选中数据全部下载
      let idArr: Array<String> = []; // id多选
      for (let key in directoryRef.value.pagingLocalData) {
        for (let obj of directoryRef.value.pagingLocalData[key]) {
          idArr.push(obj.id);
        }
      }
      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${HOST}${Api.advancedQueryBatchDownload}`, true);
      xhr.setRequestHeader('token', accessToken);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.responseType = 'blob';
      xhr.onload = function () {
        if (this.status == 200) {
          const blob = new Blob([this.response], { type: 'contentType' });
          const contentDisposition = xhr.getResponseHeader('content-disposition');
          let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
          filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
          const a = document.createElement('a');
          a.href = window.URL.createObjectURL(blob);
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(Api.advancedQueryBatchDownload);
        }
      };
      xhr.send(JSON.stringify({ ids: idArr }));
    } else if (item.key === 'DYNAMICLOCALICONS' && item.value.value === '状态变更') {
      if (!item.state.selected.length) {
        message.warning('请先选中一个选项');
      } else {
        Modal.confirm({
          title: '是否确定变更档案状态为正式档案',
          icon: createVNode(ExclamationCircleOutlined),
          autoFocusButton: null,
          okText: '确定',
          cancelText: '取消',
          onOk() {
            const ids = item.state.selected.map((item) => {
              return item.id;
            });
            advancedQueryUpdateStatus({ ids }).then((res) => {
              if (res.success) {
                message.success('变更成功');
                directoryRef.value.getData();
              }
            });
          },
          onCancel() {},
          class: 'test'
        });
      }
    }
  });

onMounted(() => {
  getArchivesTypeTree();
});

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
  message.destroy();
});

// 获取查询档案类型目录树
const getArchivesTypeTree = () => {
  advancedQueryArchivesTypeTree({ name: state.searchName }).then((res) => {
    let changeData = JSON.stringify(res.data);
    changeData = changeData.replace(/id/gi, 'key');
    changeData = changeData.replace(/name/gi, 'title');
    state.treeData = [...JSON.parse(changeData)];
  });
};

// 树选择，档案类型分页查询
const handleNodeSelect = (selectedKeys, { node }) => {
  dyTableConfig.queryUrl = Api.advancedQueryFindPageByTypeId;
  dyTableConfig.params = { id: node.key };
  directoryRef.value.getData();
};

// 下载文件
const downloadFile = (url) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
};
</script>

<style lang="less" scoped>
:deep(.tree-warpper) {
  .ant-tree-switcher {
    line-height: 36px;
  }
  .ant-tree-node-content-wrapper {
    min-height: 36px;
    line-height: 36px;
    &.ant-tree-node-selected {
      background-color: #e5eefd;
      color: #005aea;
    }
  }
}
.hide-text {
  width: 35px;
  padding-top: 7px;
  text-align: center;
}
.p-4 {
  padding: 2rem 2rem 1rem 1rem;
}
.tree-icon {
  text-align: right;
  position: relative;
  .anticon-left {
    position: absolute;
    right: -25px;
    top: -25px;
  }
}
</style>
